#!/usr/bin/python
# -*- coding: utf8 -*- 
import sys
import time
import cv
from threading import Thread
from UDPClient import UDPClient
from Shaders import Shaders
from BattleArena import BattleArena
from Weapon import Weapon
from Score import Score
from OpenGL.GL import *
from OpenGL.GL import shaders
from OpenGL.GLUT import *

class Game:
	
	weapon = None
	battleArena = None
	shader = None
	conn = None
	arms = None
	
	modelview = None
	data = None
	result = None
	capture = None
	width = None
	height = None
	player = None
	score = None

	
	def __init__(self,argv,width,height):
		self.width = width
		self.height = height
		self.main(argv,width,height)

	def initCamera(self,width,height):
		capture = cv.CaptureFromCAM(0)
		cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, width)
		cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, height)
		return capture
	
	def main(self,argv, width, height):
		glutInit(argv)
		glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH)
		glutInitWindowSize(width, height)
		
		glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH)-width)/2,
                       (glutGet(GLUT_SCREEN_HEIGHT)-height)/2)
		
		window = glutCreateWindow("Pong")
		self.init(width,height)

		glutDisplayFunc(self.display)
		glutIdleFunc(self.idle)
		glutKeyboardFunc(self.keyboard)
		glutTimerFunc(2000, self.getWeapon, 0);
		glutMainLoop()
			
	def init(self,width,height):
		glDepthFunc(GL_NEVER) 
		sh = Shaders()
		VERTEX_SHADER = shaders.compileShader(sh.VERTEX(), GL_VERTEX_SHADER)
		FRAGMENT_SHADER = shaders.compileShader(sh.FRAGMENT(), GL_FRAGMENT_SHADER)
		self.shader = shaders.compileProgram(VERTEX_SHADER, FRAGMENT_SHADER)
		self.modelview = glGetUniformLocation(self.shader, "modelview")
		self.capture = self.initCamera(width,height)
		
		self.battleArena = BattleArena(self.shader)
		self.weapon = Weapon()
		self.score = Score()
		glClearColor( 0.0, 0.0, 0.0, 0.0 )
			
	def display(self):
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
		glUseProgram(self.shader)
		self.battleArena.display(self.modelview, self.score)
		glFlush()
		glutSwapBuffers()
		
	def keyboard(self,k,x,y):
		if ord(k) == 119:
			self.battleArena.moveP1(True)
		if ord(k) == 115:
			self.battleArena.moveP1(False)
		
		
		if ord(k) == 27: # Escape
			sys.exit(0)
		
		glutPostRedisplay()
	
	def getWeapon(self,arg):
		self.arms = self.weapon.detectWeapon(self.player)
		glutTimerFunc(0, self.getWeapon, 0);
	
	def idle(self):
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
		self.player = cv.QueryFrame(self.capture)
		if self.arms != None:
			self.battleArena.idle(self.arms, self.weapon.Y, self.score, self.modelview)#, self.conn.opponent)
		else:
			self.battleArena.idle(self.player, self.weapon.Y, self.score, self.modelview)#, self.conn.opponent)
			
		glutPostRedisplay()
		
if __name__ == "__main__":
	gg = Game(sys.argv,1280,580)
	